package com.yiyuan.app.config;


import com.alibaba.mqtt.server.ServerConsumer;
import com.alibaba.mqtt.server.config.ChannelConfig;
import com.alibaba.mqtt.server.config.ConsumerConfig;
import com.yiyuan.app.entity.constant.MQTTTopicConstant;
import com.yiyuan.app.mqtt.*;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

@Slf4j
@Configuration
@AllArgsConstructor
public class MQTTConsumerConfig {

    private final MQTTProperties mqttProperties;

    private final DeviceListener deviceListener;

    private final AppListener appListener;

    private final MachineSettleListener machineSettleListener;

    private final ClientStatusListener clientStatusListener;

    private final MachineSendSettleListener machineSendSettleListener;


    @Bean
    public ServerConsumer serverConsumer() throws IOException, TimeoutException {
        ChannelConfig channelConfig = new ChannelConfig();
        channelConfig.setDomain(mqttProperties.getDomain());
        channelConfig.setPort(mqttProperties.getPort());
        channelConfig.setInstanceId(mqttProperties.getInstanceId());
        channelConfig.setAccessKey(mqttProperties.getAccessKey());
        channelConfig.setSecretKey(mqttProperties.getSecretKey());

        ServerConsumer serverConsumer = new ServerConsumer(channelConfig, new ConsumerConfig());
        serverConsumer.start();
        log.info("ServerConsumer 服务已开启");
        // 注册客户端连接状态监听
        serverConsumer.subscribeStatus(mqttProperties.getMqttGroupId(), clientStatusListener);
        // 注册推币机消费监听
        serverConsumer.subscribeTopic(MQTTTopicConstant.FIRST_TOPIC, deviceListener);
        // 注册APP街机消费监听
//        serverConsumer.subscribeTopic(MQTTTopicConstant.APP_FIRST_TOPIC, appListener);
        // 注册街机结算消费监听
        serverConsumer.subscribeTopic(MQTTTopicConstant.IO_FIRST_TOPIC, machineSettleListener);
        // 注册街机指令消费监听
//        serverConsumer.subscribeTopic(MQTTTopicConstant.MACHINE_FIRST_TOPIC, machineSendSettleListener);
        return serverConsumer;
    }

}
